<?php

namespace app\common\model;

use app\common\model\Base;
use think\Db;

class Models extends Base {

    public function get_fields($category) {

        if (empty($category)) {
            return [];
        }

        $model = $this->model_where()->where('c.id', $category)->find();

        $data = [];
        foreach (explode(PHP_EOL, $model['fields']) as $key => $value) {

            $cols = explode(':', $value);

            if (!isset($cols[0]) || !isset($cols[1]) || !isset($cols[2]))
                continue;

            $data[$key]['name'] = isset($cols[0]) ? $cols[0] : '';
            $data[$key]['title'] = isset($cols[1]) ? $cols[1] : '';
            $data[$key]['type'] = isset($cols[2]) ? $cols[2] : '';
            $data[$key]['option'] = isset($cols[3]) ? $cols[3] : '';
        }

        return $data;
    }

    public function get_grid($category) {

        if (empty($category)) {
            return [];
        }

        $model = $this->model_where()->where('c.id', $category)->find();

        $data = [];
        foreach (explode(PHP_EOL, $model['list_grid']) as $key => $value) {

            $cols = explode(':', $value);

            if (!isset($cols[0]) || !isset($cols[1]))
                continue;

            $data[$key]['name'] = isset($cols[0]) ? $cols[0] : '';
            $data[$key]['title'] = isset($cols[1]) ? $cols[1] : '';
            $data[$key]['type'] = isset($cols[2]) ? $cols[2] : '';
        }


        return $data;
    }

    public function model_where($category = 0) {

        if ($category)
            $this->where('c.id', $category);


        $this->join('category c', 'c.models_id = a.id');

        $this->field('a.*');

        $this->alias('a');

        return $this;
    }

}
